<?php

namespace App\Http\Controllers;

use DB;

use Queue;
use App\Jobs\SendPush;
use App\Jobs\SendEmail;
use App\Jobs\SendSMS;
use App\Jobs\SendIVR;
use App\Jobs\SendWechat;

class MessageCheckController extends Controller
{
    public function index()
    {
        $nowTime = date("Y-m-d H:i:s");
        
        //可发送通知途径
        $informMethodResult = DB::table("im_inform_method")
            ->select("im_inform_method.id","im_inform_method.inform_id","im_inform_method.method_id","im_inform_method.tpl_id","im_inform_method.could_send_time")
            ->join("im_inform","im_inform.id","=","im_inform_method.inform_id")
            ->where("im_inform.is_closed",false)
            ->where("im_inform.is_deleted",false)
            ->where("im_inform_method.could_send",true)
            ->where("im_inform_method.is_sent",false)
            ->where("im_inform_method.could_send_time","<=",$nowTime)->get();
        
        $informUserMethod = []; 
        $informMethodIds  = [];
        foreach ($informMethodResult as $key => $informMethod) {
            $informId      = $informMethod->inform_id;
            $methodId      = $informMethod->method_id;
            $tplId         = $informMethod->tpl_id;
            $couldSendTime = $informMethod->could_send_time;

            $informUserResult = DB::table("im_inform_user")
                ->select("im_user_method.user_id","im_user_method.send_delay")
                ->join("im_user_method","im_user_method.user_id","=","im_inform_user.user_id")
                ->where("im_inform_user.reply_opt_id",null)
                ->where("im_inform_user.inform_id",$informId)
                ->where("im_user_method.method_id",$methodId)
                ->where("im_user_method.grade","!=",0)->get();

            foreach ($informUserResult as $user){
                $informUserMethod[] = [
                    "user_id"   => $user->user_id,
                    "inform_id" => $informId,
                    "method_id" => $methodId,
                    "tpl_id"    => $tplId,
                    "could_send_time" => date("Y-m-d H:i:s",strtotime($couldSendTime)+$user->send_delay)
                ];
            }
            $informMethodIds[] = $informMethod->id;
        }

        //插入发送队列
        DB::table("im_inform_user_method")->insert($informUserMethod);
        //更新发送状态
        DB::table("im_inform_method")->whereIn("id",$informMethodIds)->update(["is_sent"=>true,"send_time"=>$nowTime]);

        //发送
        $messageResult = DB::select("SELECT im_inform_user_method.id,im_inform_user_method.tpl_id,
            im_inform.id AS inform_id,im_inform.title,im_inform.content,im_inform.set_id,im_inform.is_urgent,im_inform.is_notcare,
            im_inform_user.id AS message_id,im_inform_user.special,im_inform_user.token,
            im_user_method.method_id,im_user_method.value,

            im_set.name AS set_name,im_set.icon AS set_icon,
            im_user.name AS sender_name,
            im_reply_opt.id AS reply_opt_id,im_reply_opt.content AS reply_opt_content,im_reply_opt.is_expected,im_reply_opt.replied_count,im_reply_opt.url_page
            FROM im_inform_user_method
            INNER JOIN im_inform ON im_inform.id = im_inform_user_method.inform_id
            INNER JOIN im_inform_user ON im_inform_user.user_id = im_inform_user_method.user_id AND im_inform_user.inform_id = im_inform_user_method.inform_id
            INNER JOIN im_user_method ON im_user_method.user_id = im_inform_user_method.user_id AND im_user_method.method_id = im_inform_user_method.method_id
            
            INNER JOIN im_set ON im_set.id = im_inform.set_id
            LEFT JOIN im_user ON im_user.id = im_inform.sender_id
            LEFT JOIN im_reply_opt ON im_reply_opt.inform_id = im_inform_user_method.inform_id
            WHERE im_inform_user_method.send_code is null AND im_inform_user_method.could_send_time <= '$nowTime'
            ");
        $messageData = [];
        foreach ($messageResult as $key => $value) {
            if(!isset($messageData[$value->id])){
                $value->reply_opt = [];
                $value->reply_url = "http://".env("APP_URL")."/m/".$value->token;
                $messageData[$value->id] = $value;
            }
            $messageData[$value->id]->reply_opt[] = [
                "id"            => $value->reply_opt_id,
                "content"       => $value->reply_opt_content,
                "is_expected"   => $value->is_expected,
                "replied_count" => $value->replied_count,
                "url_page"      => $value->url_page
            ];
        }

        $methodCount = [1=>0,2=>0,3=>0,4=>0,5=>0];
        $messageIds  = [];
        foreach ($messageData as $value) {
            $methodCount[$value->method_id]++;
            $messageIds[] = $value->id;
            switch ($value->method_id) {
                //推送
                case 1:
                    $transmissionData = [
                        "type"       => "message",
                        "message_id" => $value->message_id,
                        "inform_id"  => $value->inform_id,
                        "title"      => $value->title.$value->special,
                        "is_urgent"  => $value->is_urgent,
                        "is_notcare" => $value->is_notcare,
                        "set_id"     => $value->set_id,
                        "set_icon"   => $value->set_icon,
                        "set_name"   => $value->set_name,
                        "sender_name"=> $value->sender_name,
                        "token"      => $value->token,
                        "reply_opt"  => $value->reply_opt
                    ];
                    $data = [
                        "id"                    => $value->id,
                        "transmissionData"      => $transmissionData,
                        "clients"               => [$value->value]
                    ];
                    Queue::push(new SendPush($data));
                    break;
                //邮件
                case 2:
                    switch ($value->tpl_id) {
                        case "ptimeinform":
                            $sub = [
                                "%title%"           =>[$value->title],
                                "%content%"         =>[$value->content],
                                "%special_inform%"  =>[$value->special],
                                "%app_name%"        =>[""],
                                "%set_name%"        =>[$value->set_name],
                                "%sender_name%"     =>[$value->sender_name],
                                "%sender_email%"    =>[""],
                                "%reply_url%"       =>[$value->reply_url."?method_id=2"]
                            ];
                            break;
                        default:
                            $sub = [];
                            break;
                    }
                    $data = [
                        "id"        => $value->id,
                        "from"      => "service@timepicker.cn",
                        "to"        => [$value->value],
                        "tpl_name"  => $value->tpl_id,
                        "subject"   => "我是".$value->sender_name."，".$value->title.$value->special."。",
                        "sub"       => $sub
                    ];
                    Queue::push(new SendEmail($data));
                    break;
                //短信
                case 3:
                    switch ($value->tpl_id) {
                        case "743453":
                            $text = "【拾光通知】我是".$value->sender_name."，".$value->title.$value->special."。回复我：".$value->reply_url;
                            break;
                        default:
                            $text = "";
                            break;
                    }
                    if($text == "") break;
                    $data = [
                        "id"     => $value->id,
                        "text"   => $text,
                        "mobile" => $value->value
                    ];
                    Queue::push(new SendSMS($data));
                    break;
                //语音电话
                case 4:
                    $data = [
                        "id"            => $value->id,
                        "txt"           => "     我是".$value->sender_name."，".$value->title.$value->special."。尽快用 拾光 回复我吧！",
                        "phone"         => $value->value,
                        "sender_phone"  => ""
                    ];
                    Queue::push(new SendIVR($data));
                    break;
                //微信
                case 5:
                    switch ($value->tpl_id) {
                        case env("WECHAT_TEMP_ID"):
                            $data = [
                                "url"    => $value->reply_url."?method_id=5",
                                "color"  => "#FF0000",
                                "data"   => [
                                     "first"    => "我是".$value->sender_name."，".$value->title.$value->special,
                                     "keyword1" => $value->set_name." ".$value->sender_name,
                                     "keyword2" => date("Y-m-d H:i"),
                                     "remark"   => "点击回复我",
                                ]
                            ];
                            break;
                        default:
                            $data = "";
                            break;
                    }
                    if($data == "") break;
                    
                    $data["id"]     = $value->id;
                    $data["openid"] = $value->value;
                    $data["tpl_id"] = $value->tpl_id;

                    Queue::push(new SendWechat($data));
                    break;
                default:
                    # code...
                    break;
            }
        }


        DB::table("im_inform_user_method")
            ->whereIn("id",$messageIds)->update(["send_code"=>0,"send_time"=>$nowTime]);

        return $this::jsonResponse(false,$methodCount);

	}
}